<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>楼宇管理</title>
    <script src="../js/axios-0.18.0.js"></script>
    <script src="../js/axios-interceptors.js"></script>
    <script src="../js/vue3.js"></script>
    <script src="../js/element-plus.js"></script>
    <script src="../js/icons-vue.js"></script>
    <script src="../js/zh-cn.js"></script>
    <link href="../css/index.css" rel="stylesheet"/>
    <style>
        /* 基础背景色 */
        body {
            background-color: #f9fafb;
            padding: 20px;
        }

        /* 容器样式 */
        .building-container {
            padding: 24px;
            background-color: #fff;
            border-radius: 12px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
        }

        /* 按钮区域样式 */
        .btn-group {
            display: flex;
            gap: 10px;
            margin-bottom: 16px;
            padding: 16px;
            background-color: #f8fafc;
            border-radius: 8px;
            align-items: center;
        }

        /* 搜索区域样式 */
        .search-wrap {
            display: flex;
            justify-content: flex-end;
            margin-bottom: 20px;
            padding: 12px 16px;
            background-color: #f0f7ff;
            border-radius: 8px;
        }

        .search-wrap .el-input {
            width: 240px;
            margin-right: 10px;
            border-radius: 20px;
            border-color: #e0e7ff;
        }

        /* 表格样式 */
        .building-table {
            width: 100%;
            border-radius: 8px;
            overflow: hidden;
            margin-bottom: 20px;
            background-color: #fff;
        }

        .el-table th {
            background-color: #f0f7ff;
            color: #333;
            font-weight: 500;
            border-bottom: 1px solid #e6f7ff;
        }

        .el-table td {
            border-bottom: 1px solid #f5f7fa;
        }

        .el-table--border::after,
        .el-table--group::after,
        .el-table::before {
            background-color: #f0f0f0;
        }

        /* 表格行高和斑马纹 */
        .el-table {
            --el-table-row-height: 60px;
        }

        .el-table__row:nth-child(even) {
            background-color: #fafbfc;
        }

        /* 表格操作列按钮样式 */
        .el-table .el-button {
            margin-right: 5px;
            border-radius: 4px;
            color: #fff !important;
            transition: all 0.2s ease;
        }

        .edit-btn {
            background-color: #409eff;
            border-color: #409eff;
        }

        .edit-btn:hover {
            background-color: #66b1ff;
            border-color: #66b1ff;
            color: #fff !important;
            box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
            transform: translateY(-1px);
        }

        .delete-btn {
            background-color: #f56c6c;
            border-color: #f56c6c;
        }

        .delete-btn:hover {
            background-color: #f78989;
            border-color: #f78989;
            box-shadow: 0 2px 8px rgba(245, 108, 108, 0.3);
            transform: translateY(-1px);
        }

        /* 分页组件样式 */
        .pagination-block {
            margin-top: 16px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px 16px;
            border-top: 1px solid #f0f0f0;
            background-color: #f8fafc;
            border-radius: 8px;
        }

        .pagination-info {
            color: #666;
        }

        .el-pagination {
            --el-pagination-item-border-radius: 4px;
        }

        .el-pagination__item {
            border-radius: 4px;
            margin: 0 3px;
        }

        .el-pagination__item.active {
            background-color: #409eff;
            border-color: #409eff;
        }

        /* 按钮样式优化 */
        .el-button {
            border-radius: 20px;
            padding: 8px 20px;
            transition: all 0.3s ease;
        }

        .el-button--primary {
            background-color: #409eff;
            border-color: #409eff;
        }

        .el-button--primary:hover {
            background-color: #66b1ff;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
        }

        .el-button--success {
            background-color: #52c41a;
            border-color: #52c41a;
        }

        .el-button--success:hover {
            background-color: #73d13d;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(82, 196, 26, 0.2);
        }

        .el-button--danger {
            background-color: #f56c6c;
            border-color: #f56c6c;
        }

        .el-button--danger:hover {
            background-color: #f78989;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(245, 108, 108, 0.2);
        }

        /* 对话框样式 */
        .el-dialog {
            border-radius: 12px;
        }

        .el-dialog__header {
            border-bottom: 1px solid #f0f0f0;
            padding: 16px 20px;
            background-color: #f8fafc;
        }

        .el-dialog__body {
            padding: 20px;
            background-color: #fff;
        }

        .el-dialog__footer {
            border-top: 1px solid #f0f0f0;
            padding: 16px 20px;
            background-color: #f8fafc;
        }

        /* 表单样式 */
        .el-form-item {
            margin-bottom: 16px;
        }

        .el-input {
            border-radius: 6px;
        }

        /* 表格列内容样式 */
        .building-name {
            color: #1890ff;
            font-weight: 500;
        }

        .building-address {
            color: #666;
        }

    </style>
</head>
<body>
<div id="app">
    <div class="building-container">
        <!-- 顶部按钮区域 -->
        <div class="btn-group" style="display: flex; align-items: center;">
            <el-button @click="loadBuildings" type="primary">显示所有楼宇信息</el-button>
            <el-button @click="showAddDialog" type="success">新增楼宇</el-button>
            <el-button @click="batchDelete" type="danger">批量删除</el-button>
            <el-input placeholder="搜索楼宇名称" size="default" v-model="searchKeyword" style="width: 60%; margin-left: auto;"></el-input>
            <el-button @click="searchBuilding" type="primary" style="margin-left: 10px;">搜索</el-button>
        </div>


        <!-- 楼宇列表 -->
        <div>
            <el-table
                    :data="filteredBuildings"
                    @selection-change="handleSelectionChange"
                    border
                    class="building-table"
                    stripe
            >
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column align="center" label="楼宇编号" prop="buildingId" width="100"></el-table-column>
                <el-table-column label="名称" min-width="150" prop="buildingName">
                    <template #default="scope">
                        <div class="building-name">{{ scope.row.buildingName }}</div>
                    </template>
                </el-table-column>
                <el-table-column label="地址" min-width="200" prop="location">
                    <template #default="scope">
                        <div class="building-address">{{ scope.row.location }}</div>
                    </template>
                </el-table-column>
                <el-table-column label="备注" min-width="200" prop="remark"></el-table-column>

                <el-table-column align="center" label="操作" width="180">
                    <template #default="scope">
                        <el-button @click="handleEdit(scope.row)" class="edit-btn" size="small">
                            编辑
                        </el-button>
                        <el-button
                                @click="buildingDelete(scope.row)"
                                class="delete-btn"
                                size="small"
                                type="danger"
                        >
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>


        <!-- 分页组件 -->
        <div class="pagination-block">
            <div class="pagination-info">
                共 {{ total }} 条记录
            </div>
            <el-pagination
                    :background="true"
                    :page-sizes="[5,10,15]"
                    :total="total"
                    @current-change="handleCurrentChange"
                    @size-change="handleSizeChange"
                    layout="sizes, prev, pager, next, jumper"
                    v-model:current-page="pageNum"
                    v-model:page-size="pageSize"
            ></el-pagination>
        </div>
    </div>

    <!-- 编辑/新增对话框 -->
    <el-dialog
            :title="dialogTitle"
            v-model="dialogVisible"
            :before-close="closeDialog"
            width="500px">
        <el-form :model="formData" :rules="rules" label-width="100px" ref="formRef">
            <el-form-item label="楼宇编号">
                <el-input :disabled="true" placeholder="自动生成" v-model="formData.buildingId"></el-input>
            </el-form-item>
            <el-form-item label="楼宇名称" prop="buildingName">
                <el-input autocomplete="off" v-model="formData.buildingName"></el-input>
            </el-form-item>
            <el-form-item label="所在地址" prop="location">
                <el-input v-model="formData.location"></el-input>
            </el-form-item>
            <el-form-item label="楼宇备注">
                <el-input rows="3" type="textarea" v-model="formData.remark"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="closeDialog">取消</el-button>
                <el-button @click="submitForm" type="primary">提交</el-button>
            </div>
        </template>
    </el-dialog>
</div>

<script>
    const {createApp, reactive, ref, computed, onMounted} = Vue;
    const {ElMessage, ElMessageBox} = ElementPlus;

    const app = createApp({
        setup() {
            // 分页相关
            const pageNum = ref(1);
            const pageSize = ref(10);
            const total = ref(0);

            // 搜索关键字
            const searchKeyword = ref('');

            // 楼宇单列数据
            const buildings = ref([]);

            // 过滤后的楼宇列表
            const filteredBuildings = computed(() => {
                if (!searchKeyword.value) return buildings.value;
                return buildings.value.filter(item =>
                    item.buildingName.toLowerCase().includes(searchKeyword.value.toLowerCase())
                );
            });

            // 编辑的表单数据
            const formData = ref({
                buildingId: '',
                buildingName: '',
                location: '',
                remark: ''
            });

            // 对话框状态
            const dialogVisible = ref(false);
            const dialogTitle = ref('新增楼宇');

            // 选中的行
            const multipleSelection = ref([]);

            // 表单验证规则
            const rules = ref({
                buildingName: [
                    {required: true, message: '请输入楼宇名称', trigger: 'blur'},
                    {min: 2, max: 20, message: '名称长度在2到20个字符之间', trigger: 'blur'}
                ],
                location: [
                    {required: true, message: '请输入所在地址', trigger: 'blur'}
                ]
            });

            // 表单引用
            const formRef = ref(null);

            // 加载所有楼宇信息
            const loadBuildings = () => {
                axios.get(`/building/${pageNum.value}/${pageSize.value}`)
                    .then(resp => {
                        buildings.value = resp.data.obj.data
                        total.value = resp.data.obj.total
                    })
                    .catch((error) => {
                        ElMessage.error(error.response.data.msg)
                    })
            }

            // 根据关键字搜索楼宇
            const searchBuilding = () => {
                if (searchKeyword.value.trim() === '') {
                    // 若搜索关键字为空，加载所有楼宇
                    loadBuildings();
                    return;
                }
                axios.get(`/building/selectBuildingByName/${searchKeyword.value}`)
                    .then(resp => {
                        buildings.value = resp.data.obj.data;
                        total.value = resp.data.obj.total;
                    })
                    .catch(error => {
                        ElMessage.error(error.response.data.msg);
                    });
            };

            // 显示新增楼宇对话框
            const showAddDialog = () => {
                formData.buildingId = ''
                formData.buildingName = ''
                formData.location = ''
                formData.remark = ''
                dialogVisible.value = true;
            };

            // 处理编辑操作（接收当前行数据）
            const handleEdit = (row) => {
                console.log(row);
                formData.value = {
                    buildingId:row.buildingId,
                    buildingName:row.buildingName,
                    location: row.location,
                    remark: row.remark
                };
                dialogVisible.value = true;
            };

            // 清空校验红字信息
            const clearValid = () => {
                if (formRef && formRef.value) {
                    formRef.value.resetFields();
                }
            }

            //编辑弹窗的取消方法
            const closeDialog = () => {
                clearValid();
                formData.value = {};
                dialogVisible.value = false;
            }


            // 处理删除操作
            const buildingDelete= (row) => {
                ElMessageBox.confirm(
                    '确定要删除该楼宇吗？',
                    '删除确认',
                    {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                ).then(() => {
                    console.log("进入handleDelete方法", row);
                    axios.delete(`/building/deleteById/${row.buildingId}`)
                        .then((resp) => {
                            if (resp.data.obj === 1) {
                                loadBuildings()
                                ElMessage.success('删除成功')
                            }
                        })
                        .catch(error => {
                            ElMessage.error(error.response.data.msg)
                        })
                })
                    .catch(() => {
                        ElMessage({
                            type: 'info',
                            message: '取消删除',
                        })
                    })
            };

            // 处理表格选中项变化（更新选中的行数据)
            const handleSelectionChange = (val) => {
                multipleSelection.value = val;
            };

            // 批量删除选中的楼宇
            const batchDelete = () => {
                if (multipleSelection.value.length === 0) {
                    ElMessage.warning("请选择需要删除的楼宇");
                    return;
                }

                ElMessageBox.confirm('将永久删除选中的楼宇信息. 确定?', '警告', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(() => {
                    // 提取选中项的id列表
                    const ids = multipleSelection.value.map(item => item.buildingId);
                    axios.post("/building/deleteByIds",ids)
                        .then((resp) => {
                            if (resp.data.code === 200) {
                                loadBuildings()
                                ElMessage.success('删除成功')
                                multipleSelection.value = [];
                            }
                        })
                        .catch(error => {
                            ElMessage.error(error.response.data.msg)
                        });
                }).catch(() => {
                    ElMessage({
                        type: 'info',
                        message: '取消批量删除',
                    });
                });
            };

            // 提交表单（新增或编辑楼宇信息）
            const submitForm = () => {
                //判断校验是否通过
                if (formRef.value.validate(valid => {
                    if (valid) {
                        console.log("提交的buildingId:", formData.buildingId); // 检查是否有值
                        //校验通过
                        if (!formData.value.buildingId || formData.value.buildingId === '') {
                            // 新增操作
                            axios.post("/building/insertBuilding", formData.value)
                                .then((resp) => {
                                    if (resp.data.obj === 1) {
                                        ElMessage.success("添加成功")
                                        dialogVisible.value = false
                                        loadBuildings()
                                    }
                                })
                                .catch(error => {
                                    ElMessage.error(error.response.data.msg)
                                })
                        } else {
                            // 修改操作
                            axios.put("/building/updateBuilding", formData.value)
                                .then((resp) => {
                                    if (resp.data.obj === 1) {
                                        console.log("修改成功")
                                        ElMessage.success("修改成功")
                                        dialogVisible.value = false
                                        loadBuildings()
                                    }
                                })
                                .catch(error => {
                                    ElMessage.error(error.response.data.msg)
                                })
                        }
                    } else {
                        //校验不通过
                        ElMessage.error("请输入完整信息")
                    }
                })) ;

            };



            // 处理分页大小变化（更新每页显示条数）
            const handleSizeChange = (val) => {
                pageSize.value = val
                loadBuildings()
            };

            // 处理分页页码变化（更新当前页码）
            const handleCurrentChange = (val) => {
                pageNum.value = val
                loadBuildings()
            };

            onMounted(() => {
                loadBuildings()
            })

            return {
                // 数据
                buildings,
                filteredBuildings,
                searchKeyword,
                formData,
                dialogVisible,
                dialogTitle,
                multipleSelection,
                pageNum,
                pageSize,
                total,
                rules,
                formRef,

                // 方法
                loadBuildings,
                searchBuilding,
                showAddDialog,
                handleEdit,
                batchDelete,
                submitForm,
                handleSelectionChange,
                handleSizeChange,
                handleCurrentChange,
                buildingDelete,
                clearValid,
                closeDialog,
            };
        }
    });

    // 注册Element Plus
    app.use(ElementPlus, {
        locale: ElementPlusLocaleZhCn
    });

    // 注册图标
    for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
        app.component(key, component);
    }

    app.mount('#app');
</script>
</body>
</html>
